<template>
  <Form ref="formRef" :data="model" @submit-success="onOk" layout="vertical">
    <FormItem field="mobile" :rules="{ required: true, message: '手机不能为空' }" :show-title="false">
      <Input v-model="model.account" placeholder="手机号">
        <template #prefix>
          <IconUser />
        </template>
      </Input>
    </FormItem>
    <FormItem field="captcha" :rules="{ required: true, message: '短信验证码不能为空' }" :show-title="false">
      <Input v-model="model.captcha" placeholder="短信验证码">
        <template #prefix>
          <IconLock />
        </template>
      </Input>
      <Button class="ml8" :disabled="isDisabled" @click="onSendSms" :text="text" />
    </FormItem>
    <Space direction="vertical">
      <Button type="primary" block html-type="submit" :loading="loading" text="登录" />
    </Space>
  </Form>
</template>

<script setup lang="ts">
import { Message, Form, FormItem, Button, Input, Space } from '@idmy/ui'
import { IconLock, IconUser } from '@idmy/ui-icon'
import { getUrlParam, useCountdown, useLoading } from '@idmy/core'
import { passwordLogin, sendSmsCaptcha } from './services'

const model = reactive({
  account: null,
  captcha: null,
  redirectUri: getUrlParam('redirectUri'),
})

const { text, isDisabled, onSend } = useCountdown(async () => {
  await sendSmsCaptcha(model.account)
  Message.info('验证码已发送')
})

const formRef = ref(null)
const onSendSms = async () => {
  const tmp = await formRef.value.validateField('account')
  tmp?.account?.isRequiredError || (await onSend())
}

const [onOk, loading] = useLoading(async () => {
  await passwordLogin(model)
})
</script>
